from groups.models import *
from django.shortcuts import render_to_response, get_object_or_404 
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from groups.forms import GroupForm
from thoughts.models import Thought
from authors.models import Invitation,Author


@csrf_exempt
def main(request,username):
   if request.user.is_anonymous(): 
      groups = ''
      myauthors =''
   else: 
      groups  = Group.objects.filter(owner = request.user)
      try:
           me = Author.objects.get(user = request.user)
           myauthors  = me.myauthors.all()
      except Author.DoesNotExist:
           myauthors=''  

   return render_to_response ( 
        'home.html',
        {
         'is_authenticated' : request.user.is_authenticated(),
         'groups' :  groups,
         'myauthors': myauthors,
         'thoughts' : publsihed_thoughts(),
         'invitations_nb': Invitation.objects.filter(to_user__pk = request.user.id).exclude(status=True).count(),
                   # confirmed = False, not confirmed = Flase 
        },
        context_instance = RequestContext(request)
        )

def publsihed_thoughts():
    thoughts =  Thought.objects.filter(published = True)
    return thoughts
    

@csrf_exempt
def index(request):
   if request.user.is_anonymous():
       return render_to_response ( 
           'base.html',
           {
           'is_authenticated' : request.user.is_authenticated(),
           },
           context_instance = RequestContext(request)
       )
   else:
      return HttpResponseRedirect("/"+request.user.username+"/")

def publsihed_thoughts():
    thoughts =  Thought.objects.filter(published = True)
    return thoughts
    
